package struct;

import com.alibaba.fastjson.JSONObject;
import struct.enums.ServiceType;
import struct.enums.State;

public class ServiceInfo {
    public static final String SERVICE_TYPE_FIELD = "service_type";
    public static final String SERVICE_CONFIG_FIELD = "config";
    private static final String SERVICE_STATE_FIELD = "state";
    private static final String SERVICE_RESULT_FIELD = "result";

    public ServiceType type;
    public String appName;
    public State state;
    public ServiceConfig config;
    public ServiceResult result;
    public JSONObject jo;

    public ServiceInfo(ServiceType type, String appName, State state, ServiceConfig config, ServiceResult result) {
        this.type = type;
        this.appName = appName;
        this.state = state;
        this.config = config;
        this.result = result;
    }

    public ServiceInfo(JSONObject obj) {
        this.jo = obj;
        this.type = ServiceType.fromString(obj.getString(SERVICE_TYPE_FIELD));
        this.appName = obj.getString(AppInfo.APP_NAME_FIELD);
        this.state = State.fromString(obj.getString(SERVICE_STATE_FIELD));
        if (type == ServiceType.CTX) {
            try {
                this.config = CtxServiceConfig.fromJSONString(obj.getString(SERVICE_CONFIG_FIELD));
            } catch (Exception ignored) {}
            try {
                this.result = CtxServiceResult.fromJSONString(obj.getString(SERVICE_RESULT_FIELD));
            } catch (Exception ignored) {}
        } else {
            try {
                this.config = InvServiceConfig.fromJSONString(obj.getString(SERVICE_CONFIG_FIELD));
            } catch (Exception ignored) {}
            try {
                this.result = InvServiceResult.fromJSONString(obj.getString(SERVICE_RESULT_FIELD));
            } catch (Exception ignored) {}
        }
    }

    public ServiceInfo(ServiceType type, String appName, State state, ServiceConfig config, JSONObject extraObj){
        this.jo = new JSONObject();
        jo.put(SERVICE_TYPE_FIELD, type.toString());
        jo.put(AppInfo.APP_NAME_FIELD, appName);
        jo.put(SERVICE_STATE_FIELD, state.toString());
        jo.put(SERVICE_CONFIG_FIELD, config.toJSONObject());
        jo.putAll(extraObj);
    }

    @Override
    public String toString() {
        if (jo != null) return jo.toJSONString();
        return this.toJSONObject().toJSONString();
    }

    public JSONObject toJSONObject() {
        if (jo != null) return jo;
        jo = new JSONObject();
        jo.put(SERVICE_TYPE_FIELD, type.toString());
        jo.put(AppInfo.APP_NAME_FIELD, appName);
        jo.put(SERVICE_STATE_FIELD, state.toString());
        jo.put(SERVICE_CONFIG_FIELD, config == null ? null : config.toJSONObject());
        jo.put(SERVICE_RESULT_FIELD, result == null ? null : result.toJSONObject());
        return jo;
    }
}
